﻿using System;
using Expect.Core.Interfaces;

namespace Expect.Core.Fixtures
{
    /// <summary>
    /// Fixture to feed properties of an object in the context
    /// </summary>
    public class ObjectFeedFixture : AbstractFixture, ITableFixtureFormat
    {
        /// <summary>
        /// Name of the object in context data
        /// </summary>
        protected string objectName;

        /// <summary>
        /// Fixture constructor
        /// </summary>
        /// <param name="objName"></param>
        public ObjectFeedFixture(string objName)
        {
            objectName = objName;
        }

        /// <summary>
        /// Execute the fixture for the provided row
        /// </summary>
        public override bool? RunRow()
        {
            if (Row.Cells.Count != 2) 
                throw new InvalidOperationException("ObjectFeedFixture rows must have 2 columns");
            if (!Context.Data.ContainsKey(objectName))
                throw new InvalidOperationException("ObjectFeedFixture cannot find object " + objectName + " in the context data");

            var obj = Context.Data[objectName];
            string propname = Context.NameProvider.ElementName(Row.Cells[0].Text);
            if (Context.SetObjectFieldOrProperty(obj, propname, null, Row.Cells[1].Text))
            {
                Row.Cells[0].Status.Success = true;
                Row.Cells[1].Status.Success = true;
                Row.Status.Success = true;
                return true;
            }

            return false;
        }
    }
}
